package com.nettyBasic.bothWayChannel;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * @author： pang-yun
 * @date： 2021-09-14 13:29
 * 功能目的 ：用于  双向通道客户端
 * <p>
 * //建议使用 ctx.alloc 创建 ByteBuf
 */

public class BothWayClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(
                        new ChannelInitializer<NioSocketChannel>() {

                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new StringEncoder());
                                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                        //建议使用 ctx.alloc 创建 ByteBuf
                                        ByteBuf buffer = ctx.alloc().buffer();
                                        // 首次建立连接时 发送 hello
                                        buffer.writeBytes("hello,this is Client".getBytes());
                                        ctx.writeAndFlush(buffer);
                                    }

                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        ByteBuf byteBuf = msg instanceof ByteBuf ? (ByteBuf) msg : null;
                                        System.out.println(byteBuf.toString(Charset.defaultCharset()));
                                    }
                                });
                            }
                        }
                ).connect(new InetSocketAddress(9999));
        Channel channel = channelFuture.sync().channel();
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String s = scanner.nextLine();
                if ("quit".equals(s)) {
                    channel.close();
                    break;
                }
                channel.writeAndFlush(s);
            }

        }, "input").start();


        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println("客户端已关闭！");
                eventLoopGroup.shutdownGracefully();
            }
        });
    }
}
